import React from 'react';

import { Button, message, Modal } from 'antd';
import { isFunction } from 'lodash';

import { inject, observer } from 'mobx-react';
import { toJS } from 'mobx';

import {
  WeaReqTop,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaUpload,
  WeaDialog,
  WeaNewScroll,
  WeaLocaleProvider,
} from 'ecCom';
import { WeaTableNew } from 'comsMobx';

const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;

import '../style/detail.less';
import CustomButton from './FileView/CustomButton';

const confirm = Modal.confirm;

const trans = (str = '') => {
  const arr = str.split('&');
  const obj = {};
  arr.forEach((item) => {
    if (item) {
      // const _item = item.split('=');
      // obj[_item[0]] = _item[1];
      let index = item.indexOf('=');
      let _key = item.slice(0, index);
      let _value = item.slice(index + 1);
      obj[_key] = _value;
    }
  });
  return obj;
};

@inject('docFileViewStore', 'documentDetailStore')
@observer
class FileView extends React.Component {
  constructor(props) {
    super(props);
    const idReg = window.location.search.match(/(\?|\&)id=\d+/g);
    this.isIE = !!window.ActiveXObject || 'ActiveXObject' in window;
    const isEdit = props.location.query.ieEdit == '1' ? { isEdit: '1' } : {};
    this.state = {
      docid: idReg && idReg.length === 1 ? idReg[0].split('=')[1] : '',
      search: window.location.search || '',
      fileid: window.location.search.match(/imagefileId=\d+/g)[0].replace('imagefileId=', '')
      || props.location.query.id || '',
      upStatus: '',
      fileVersionVisible: false,
      list: [],
      ...isEdit,
      loadingBtn: false,
      loading: false,
      isIE: this.isIE,
    };

    // let agent = window.navigator.userAgent.toLowerCase();
    // if(agent.indexOf("android")!==-1 || agent.indexOf("iphone")!==-1){
    //   let url = `/spa/document/static4mobile/index.html#/attach/${this.state.fileid}`;
    //   if(window.em && (typeof window.em.checkJsApi === 'function') && window.em.checkJsApi('openLink')){
    //     window.em.openLink({
    //       url:url,
    //       openType:1
    //     });
    //   }else{
    //     var _win = window;
    //     _win.location = url;
    //   }
    // }
    window.__onRightMenuClick = this.onRightMenuClick.bind(this);
  }

  componentDidMount() {
    // 一些初始化请求
    const { docFileViewStore } = this.props;
    const { search } = this.state;
    docFileViewStore.getBasic(search);
    if (window.__convertFile) {
      docFileViewStore.convertFile(trans(window.__convertFile));
    }
    if (this.state.isEdit == '1') {
      window.onbeforeunload = function (e) {
        e = e || window.event;
        if (e) {
          e.returnValue = '关闭提示';
        }
        return '关闭提示';
      };
    }
  }

  componentWillUnmount() {
    window.onbeforeunload = undefined;
  // 组件卸载时一般清理一些状态
  }

  onRightMenuClick = (key) => {
    const { docFileViewStore } = this.props;
    const { rightMenus } = docFileViewStore;
    const that = this;
    const { documentDetailStore } = this.props;
    if (key === 'BTN_DOWNLOAD' || key == 'BTN_SOURCE_DOC') {
      rightMenus.forEach((btn) => {
        if (btn.type === key) {
          if (key == 'BTN_DOWNLOAD') {
            // open(`/weaver/weaver.file.FileDownload?${btn.params}${window.__moudleParams}`);

		    if (window.__docisLock) {
				try {
					document.getElementById('webOffice').contentWindow.WebSaveLocal();
					// iframe1.contentWindow.WebSaveLocal();
				} catch (e) {
					open(`/weaver/weaver.file.FileDownload?${btn.params}${window.__moudleParams}`);
				}
             //   }else if(!window.__is2015Open && (!!window.ActiveXObject || "ActiveXObject" in window )){
			} else {
				open(`/weaver/weaver.file.FileDownload?${btn.params}${window.__moudleParams}`);
            }
          } else if (key == 'BTN_SOURCE_DOC') {
            open(`/spa/document/index.jsp?${btn.params}${window.__moudleParams}#/main/document/detail`);
          }
        }
      });
    } else if (key == 'BTN_ACC_VERSION') {
      rightMenus.forEach((btn) => {
        if (btn.type === key) {
          that.openVesion();
        }
      });
    } else if (key == 'BTN_EDIT') {
      documentDetailStore.setAttachHideContent(true);
      rightMenus.forEach((btn) => {
        if (btn.type === key) {
          documentDetailStore.docfileisCheckOut({ docid: this.state.docid, resource: 'attach', params: btn.params });
        }
      });
    } else if (key == 'BTN_SUBMIT') {
      this.setState({ loadingBtn: true });

      if (window.__useWpsView && !window.__wpsSaved) {
      	window.sendSaveMsg(key);
      	return;
      }

      window.onbeforeunload = undefined;
      rightMenus.forEach((btn) => {
        if (btn.type === key && isFunction(saveDocument)) {
          const docDatas = saveDocument();
          const id = window.location.search.match(/id=\d+/g)[0].replace('id=', '');
          const imagefileId = window.location.search.match(/imagefileId=\d+/g)[0].replace('imagefileId=', '');
          if (docDatas.off_status == 1) {
            docFileViewStore.docAccSave({
              id: id || '',
              newfileid: docDatas.off_imagefileid || '',
              off_name: docDatas.off_name || '',
              oldfileid: imagefileId || '',
            }, () => {
              this.setState({ loadingBtn: false });
            });
          } else {
            this.setState({ loadingBtn: false });
            message.error(getLabel(30651, '操作失败'));
          }
        }
      });
    } else if (key === 'BTN_SAVE') {
        document.getElementById('ofdshow').contentWindow.saveFile();
    }
  }

  // title
  onChangeList = (ids, l) => this.setState({ list: l })
  onUploadingList = (s) => {
    const { list, fileid } = this.state;
    const { docFileViewStore } = this.props;
    this.setState({ upStatus: s });
    s === 'uploaded' && list.length === 1 && docFileViewStore.docAccReplace({
      id: this.state.docid,
      oldfileid: fileid,
      newfileid: list[0].fileid,
    });
  }
  onUploadingListLocal = (s) => {
    const { list, loading } = this.state;
    if (s === 'uploaded' && list.length === 1 && window.changeOfficeFile) {
      window.changeOfficeFile(list[0].fileid);
       this.setState({ loading: false });
    } else if (s === 'error') {
       this.setState({ loading: false });
    } else if (!loading) {
       this.setState({ loading: true });
    }
  }
  getButtons() {
    const { upStatus, loadingBtn, loading } = this.state;
    const { docFileViewStore } = this.props;
    let { rightMenus } = docFileViewStore;
    const btnArr = [];
    rightMenus = toJS(rightMenus).filter(menu => menu.isTop === '1');
    rightMenus.forEach((btn) => {
      btnArr.push(
        btn.type === 'BTN_ACC_REPLACE' ?
          <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@npt1ox@${btn.type}`}
            style={{ paddingTop: 0 }}
            title={getLabel(517712, '替换附件')}
            uploadUrl="/api/doc/upload/uploadFile"
            category="string"
            multiSelection={false}
            maxFilesNumber={1}
            maxUploadSize={btn.customData.maxUploadSize}
            limitType={btn.customData.limitType}
            onChange={this.onChangeList}
            onUploading={this.onUploadingList}
          >
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@h0dbgu@${btn.type}_btn`} type="primary" loading={upStatus === 'uploading'}>{btn.menuName}</Button>
          </WeaUpload>
          :
          (
          btn.type === 'BTN_OPEN_LOCAL_FILE' ?
          <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@psxp18@${btn.menuName}`}
            style={{ paddingTop: 0 }}
            title={getLabel(16381, '打开本地文件')}
            uploadUrl="/api/doc/upload/uploadFile"
            category="string"
            multiSelection={false}
            maxFilesNumber={1}
            maxUploadSize={btn.customData.maxUploadSize}
            limitType={btn.customData.limitType}
            onChange={this.onChangeList}
            onUploading={this.onUploadingListLocal}
          >
	          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@41w3xc@${btn.menuName}`} disabled={loading || loadingBtn} type="primary">{btn.menuName}</Button>
	        </WeaUpload>
          :
          <CustomButton ecId={`${this && this.props && this.props.ecId || ''}_Button@ineh14@${btn.menuName}`} type="primary" disabled={loading} loading={loadingBtn} btn={btn} onRightMenuClick={this.onRightMenuClick}>
            {btn.menuName}
          </CustomButton>
          ),
      );
    });
    return btnArr;
  }

  getRightMenu() {
    const { upStatus, list, fileid, loadingBtn, loading, isIE } = this.state;
    const { docFileViewStore } = this.props;
    const { rightMenus } = docFileViewStore;
    const btnArr = [];
    toJS(rightMenus).forEach((btn) => {
      btn.type !== 'BTN_ACC_REPLACE' && btn.type !== 'BTN_OPEN_LOCAL_FILE' && btnArr.push({
        key: btn.type,
        icon: <i className={btn.menuIcon} />,
        content: btn.menuName,
        onClick: this.onRightMenuClick,
      });
      let com = {
        key: btn.type,
        icon: <i className={btn.menuIcon} />,
        content: btn.menuName,
        onClick: this.onRightMenuClick,
        title: btn.menuName,
      };
        if (btn.type === 'BTN_ACC_REPLACE') {
          com.content = (
            <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@g9dzai@${btn.type}`}
              className="replace-file"
              style={{ paddingTop: 0 }}
              title={btn.menuName}
              uploadUrl="/api/doc/upload/uploadFile"
              category="string"
              multiSelection={false}
              maxFilesNumber={1}
              maxUploadSize={btn.customData.maxUploadSize}
              limitType={btn.customData.limitType}
              onChange={this.onChangeList}
              onUploading={this.onUploadingList}
            >
             <div style={{ paddingLeft: isIE ? 42 : '' }}>{btn.menuName}</div>
            </WeaUpload>);
             btnArr.push(com);
          }

          if (btn.type === 'BTN_OPEN_LOCAL_FILE') {
            com.content = (
              <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@o7ksuw@${btn.type}`}
                className="replace-file"
                style={{ paddingTop: 0 }}
                title={btn.menuName}
                uploadUrl="/api/doc/upload/uploadFile"
                category="string"
                multiSelection={false}
                maxFilesNumber={1}
                maxUploadSize={btn.customData.maxUploadSize}
                limitType={btn.customData.limitType}
                onChange={this.onChangeList}
                onUploading={this.onUploadingListLocal}
              >
                <div style={{ paddingLeft: isIE ? 42 : '' }}>{btn.menuName}</div>
              </WeaUpload>);
          }
    });
    return btnArr;
  }

  openVesion = () => {
    const { docFileViewStore } = this.props;
    const { fileid } = this.state;
    docFileViewStore.doSearch({ imagefileid: fileid });
    this.setState({ fileVersionVisible: true });
  }

  closeVersion = () => {
    this.setState({ fileVersionVisible: false });
  }

  // 附件操作

  onOperatesClick = (record, index, operate, flag) => {
    flag === '0' && open(`/weaver/weaver.file.FileDownload?fileid=${record.imagefileid}`
      + `&download=1${window.__moudleParams}`);
  }
  getFileVersion() {
    const { docFileViewStore } = this.props,
	{ tableStore } = docFileViewStore;
    const { fileVersionVisible } = this.state;
    return (
      <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@huyaho`}
        title={getLabel(19587, '版本信息')}
        style={{ width: 800 }}
        maskClosable={false}
        visible={fileVersionVisible}
        onCancel={this.closeVersion}
        buttons={[
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@tlwsh3@fileview-version-dialog-cancel`}
            type="ghost"
            onClick={this.closeVersion}
          >{getLabel(309, '关闭')}</Button>,
        ]}
      >
        <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@qmrjxc`} scrollId="wea_doc_detail_content_file_version" height="100%">
          <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@r38hne`}
            comsWeaTableStore={tableStore}
            onOperatesClick={this.onOperatesClick}
          />
        </WeaNewScroll>
      </WeaDialog>
    );
  }

  render() {
    const { docFileViewStore, documentDetailStore } = this.props;
    const { attachHideContent } = documentDetailStore;
    const { loading, basicInfo } = docFileViewStore;
    const { fileVersionVisible } = this.state;
    const prevname = basicInfo.prevname || '';
    const title = basicInfo.imagefilename || '';
    const versionname = basicInfo.versionname || '';
    const preTitle = $('.wea-new-top-req-title-text').html() || window.__preTitle || '';
    const onlyUrl4Content = window.__onlyUrl4Content;
    const preContent = onlyUrl4Content ? window.__preContent : $('.wea-doc-detail-content-main').html() || window.__preContent || '';
    // 设置页标题
    if (basicInfo.imagefilename && document.title != basicInfo.imagefilename) {
      document.title = basicInfo.imagefilename;
    }
    return (
      <div className="wea-doc-detail">
        <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@7y45vr`} datas={this.getRightMenu()}>
          <WeaReqTop ecId={`${this && this.props && this.props.ecId || ''}_WeaReqTop@5e7u1s`}
            title={Object.keys(basicInfo).length === 0
              ? <span dangerouslySetInnerHTML={{ __html: preTitle }} />
              : <span style={{ marginLeft: 8 }}><span className="wea-new-top-req-title-label">{prevname} </span>{title}
                {(versionname == '' || versionname == 'V0') ? '' :
                  (<span style={{ marginLeft: 3 }}>{'('}<span className="wea-new-top-req-title-version"
                    onClick={this.openVesion}
                  >{versionname}</span>{')'}</span>)
                }
              	</span>
            }
            loading={loading}
            icon={<i className="icon-coms-doc" />}
            iconBgcolor="#df583a"
            replaceTab={<span style={{ display: 'block', height: 37 }} />}
            buttons={this.getButtons()}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick}
          >
            {!onlyUrl4Content ? <div className="wea-doc-detail-content-main"
              style={fileVersionVisible || (attachHideContent && (!!window.ActiveXObject || 'ActiveXObject' in window))
                  	? { height: '1px' } : { height: '100%' }}
              dangerouslySetInnerHTML={{ __html: preContent }}
            /> :
            <div className="wea-doc-detail-content-main"
              style={fileVersionVisible || (attachHideContent && (!!window.ActiveXObject || 'ActiveXObject' in window)) ? { height: '1px' } : { height: '100%' }}
            >
                <iframe id="webOffice" src={preContent} style={{ display: 'block', width: '100%', height: '100%', border: 0 }} />
            </div>}
            {this.getFileVersion()}
          </WeaReqTop>
        </WeaRightMenu>
      </div>
    );
  }
}

export default FileView;
